﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.CardAcct.Entitys;
using PARK.CardAcct.Entitys.Dto.BaseEmployeeWechat;
using PARK.CardAcct.Interfaces;
using System.Text;
using System.Data;
using PARK.System.Entitys.Model.Permission.User;
using PARK.System.Interfaces.System;
using PARK.CardAcct.Entitys.Dto.employee;
using KYSharp.SM;

namespace PARK.CardAcct.BaseEmployeeWechat
{
    /// <summary>
    /// 微信认证服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Card", Name = "EmployeeWechat", Order = 200)]
    [Route("api/card/[controller]")]
    public class EmployeeWechatService : IEmployeeWechatService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<EmployeeWechatEntity> _baseEmployeeWechatRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly ISysCacheService _sysCacheService;
        private readonly ISysConfigService _sysConfigService; //系统配置仓储

        /// <summary>
        /// 初始化一个<see cref="EmployeeWechatService"/>类型的新实例
        /// </summary>
        public EmployeeWechatService(
            ISqlSugarRepository<EmployeeWechatEntity> baseEmployeeWechatRepository,
            IUserManager userManager,
            ISysCacheService sysCacheService,
            ISysConfigService sysConfigService)
        {
            _baseEmployeeWechatRepository = baseEmployeeWechatRepository;
            _db = _baseEmployeeWechatRepository.Context;
            _userManager = userManager;
            _sysCacheService = sysCacheService;
            _sysConfigService = sysConfigService;
        }

        /// <summary>
        /// 获取微信认证
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<EmployeeWechatEntity>().FirstAsync(p => p.WId == id);
            var output = entity.Adapt<EmployeeWechatInfoOutput>();

            #region 手机号解密处理
            try
            {
                if (!string.IsNullOrEmpty(entity.MobilePhoneSf) && entity.MobilePhoneSf.Length > 0)
                {
                    //加密手机号
                    SM4Utils sm4 = new SM4Utils();
                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                    sm4.hexString = false;
                    //解密
                    output.mobilePhone = sm4.Decrypt_ECB(entity.MobilePhoneSf);
                }
            }
            catch
            {
                output.mobilePhone = "";
            }
            #endregion

            return output;
        }

        /// <summary>
		/// 获取微信认证列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] EmployeeWechatListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "regDate" : input.sidx;
                //注册时间
                List<string> queryRegDate = input.regDate != null ? input.regDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startRegDate = queryRegDate != null ? Ext.GetDateTime(queryRegDate.First()) : null;
                DateTime? endRegDate = queryRegDate != null ? Ext.GetDateTime(queryRegDate.Last()) : null;

                var data = await _db.Queryable<EmployeeWechatEntity>()
                    .Where(p => p.CompanyId.Equals(userInfo.companyId) && (p.IsAudit==1 || p.IsAudit==2) && p.IsDeleted==0)//权限
                    .WhereIF(!string.IsNullOrEmpty(input.keyword), p => p.Nickname.Contains(input.keyword) || p.RealName.Contains(input.keyword) || p.MobilePhone.Contains(input.keyword) || p.JobNum.Contains(input.keyword))
                     //注册日期
                    .WhereIF(queryRegDate != null, u => u.RegDate >= new DateTime(startRegDate.ToDate().Year, startRegDate.ToDate().Month, startRegDate.ToDate().Day, 0, 0, 0))
                    .WhereIF(queryRegDate != null, u => u.RegDate <= new DateTime(endRegDate.ToDate().Year, endRegDate.ToDate().Month, endRegDate.ToDate().Day, 23, 59, 59))
                    .WhereIF(!string.IsNullOrEmpty(input.isAudit), p => p.IsAudit.Equals(input.isAudit))
                    .Select(it => new EmployeeWechatListOutput
                    {
                        wId = it.WId,
                        nickname = it.Nickname,
                        avatar = it.Avatar,
                        sex = it.Sex,
                        regDate = it.RegDate,
                        jobNum = it.JobNum,
                        realName = it.RealName,
                        mobilePhone = it.MobilePhone,
                        verifCode = it.VerifCode,
                        summary = it.Summary,
                        isAudit = it.IsAudit,
                        auditUserName = it.AuditUserName,
                        auditDate = it.AuditDate
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<EmployeeWechatListOutput>.SqlSugarPageResult(data);
            }
            else
            {
                return null;
            }
        }        

        /// <summary>
        /// 删除微信认证
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<EmployeeWechatEntity>().FirstAsync(p => p.WId == id);
            _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<EmployeeWechatEntity>().Where(d => d.WId == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
        }

        #region 获取微信用户状态统计
        /// <summary>
        /// 获取微信用户状态统计
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpGet("GetAuditStatusCenQtys")]
        public async Task<dynamic> GetCtlStatusCenQtys([FromQuery] EmployeeWechatListQueryInput input)
        {

            try
            {
                var userInfo = await _userManager.GetUserInfo();
                if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
                {
                    //注册时间
                    List<string> queryRegDate = input.regDate != null ? input.regDate.Split(',').ToObeject<List<string>>() : null;
                    DateTime? startRegDate = queryRegDate != null ? Ext.GetDateTime(queryRegDate.First()) : null;
                    DateTime? endRegDate = queryRegDate != null ? Ext.GetDateTime(queryRegDate.Last()) : null;
                    StringBuilder dbSql = new StringBuilder("select IsAudit,count(0) as qty from base_employee_wechat t where IsAudit!=0 and IsDeleted=0 and CompanyId ='" + userInfo.companyId + "' ");

                    #region 查询条件
                    if (queryRegDate != null)
                    {
                        //预约时间
                        var _startRegDate = (new DateTime(startRegDate.ToDate().Year, startRegDate.ToDate().Month, startRegDate.ToDate().Day, 0, 0, 0));
                        var _endRegDate = (new DateTime(endRegDate.ToDate().Year, endRegDate.ToDate().Month, endRegDate.ToDate().Day, 23, 59, 59));
                        dbSql.AppendFormat(" and t.RegDate>='{0}'", _startRegDate);
                        dbSql.AppendFormat(" and t.RegDate<='{0}'", _endRegDate);
                    }
                    if (!string.IsNullOrEmpty(input.keyword))
                    {
                        dbSql.AppendFormat(" AND (t.Nickname like '%{0}%' or t.JobNum like '%{0}%' or t.RealName like '%{0}%' or t.MobilePhone like '%{0}%')", input.keyword);
                    }
                    #endregion

                    dbSql.Append(" group by t.IsAudit");
                    var data = await _db.SqlQueryable<DataTable>(dbSql.ToString()).ToDataTableAsync();
                    EmployeeWechatStatusOutput _output = new EmployeeWechatStatusOutput();
                    _output.IsAudit0 = 0;
                    _output.IsAudit1 = 0;
                    _output.IsAudit2 = 0;
                    _output.IsAudit3 = 0;
                    DataRow[] dr = data.Select("IsAudit=0");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.IsAudit0 = int.Parse(dr[0]["qty"].ToString());
                    }
                    dr = data.Select("IsAudit=1");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.IsAudit1 = int.Parse(dr[0]["qty"].ToString());
                    }
                    dr = data.Select("IsAudit=2");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.IsAudit2 = int.Parse(dr[0]["qty"].ToString());
                    }
                    dr = data.Select("IsAudit=3");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.IsAudit3 = int.Parse(dr[0]["qty"].ToString());
                    }
                    return _output;
                }
                else
                    return null;
            }
            catch (Exception)
            {
                throw PARKException.Oh("获取数据异常");
            }
        }
        #endregion

        #region 审核微信绑定用户申请
        /// <summary>
        /// 审核微信绑定用户申请
        /// </summary>
        /// <param name="id"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        [HttpPost("WeChatEyeAuditPass")]
        public async Task WeChatEyeAuditPass(string id, string flag)
        {
            try
            {
                var userInfo = await _userManager.GetUserInfo();
                var Paras = new List<SugarParameter>();
                var entity = await _db.Queryable<EmployeeWechatEntity>().FirstAsync(p => p.WId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                var isOk = 0;
                _db.BeginTran();
                if (flag.Equals("1"))
                {
                    #region 通过
                    StringBuilder dbSql = new StringBuilder("update base_employee_wechat set IsAudit=1,");
                    dbSql.AppendFormat("AuditUser='{0}',", userInfo.userId);
                    dbSql.AppendFormat("AuditUserName='{0}',", userInfo.userName);
                    dbSql.AppendFormat("AuditDate='{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    dbSql.AppendFormat(" where wId='{0}'", id);
                    isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0))
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1001);
                    }
                    else
                    {
                        StringBuilder _dbSql = new StringBuilder("update base_employee set Isauth=1,");
                        _dbSql.AppendFormat("Authtimes='{0}',", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        _dbSql.AppendFormat("MobilePhone='{0}',", entity.MobilePhone);
                        _dbSql.AppendFormat("MobilePhoneSf='{0}',", entity.MobilePhoneSf);
                        _dbSql.AppendFormat("wId='{0}'", id);
                        _dbSql.AppendFormat(" where EmployeeId='{0}'", entity.EmployeeId);
                        isOk = await _db.Ado.ExecuteCommandAsync(_dbSql.ToString(), Paras);
                        if (!(isOk > 0))
                        {
                            //回滚事务
                            _db.RollbackTran();
                            throw PARKException.Oh(ErrorCode.COM1001);
                        }
                    }
                    #endregion
                }
                else if (flag.Equals("-1"))
                {
                    #region 驳回
                    StringBuilder dbSql = new StringBuilder("delete from base_employee_wechat ");
                    dbSql.AppendFormat(" where wId='{0}'", id);
                    isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0))
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1001);
                    }
                    #endregion
                }
                else if (flag.Equals("-2"))
                {
                    #region 解除
                    StringBuilder dbSql = new StringBuilder("delete from base_employee_wechat ");
                    dbSql.AppendFormat(" where wId='{0}'", id);
                    isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0))
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1001);
                    }
                    else
                    {
                        StringBuilder _dbSql = new StringBuilder("update base_employee set Isauth=0,");
                        _dbSql.Append("Authtimes=null,wId=null");
                        _dbSql.AppendFormat(" where EmployeeId='{0}'", entity.EmployeeId);
                        isOk = await _db.Ado.ExecuteCommandAsync(_dbSql.ToString(), Paras);
                        if (!(isOk > 0))
                        {
                            //回滚事务
                            _db.RollbackTran();
                            throw PARKException.Oh(ErrorCode.COM1001);
                        }
                    }
                    #endregion
                }
                _db.CommitTran();
            }
            catch (Exception ex)
            {
                throw PARKException.Oh(ErrorCode.COM1003);
            }
        }
        #endregion

        #region 小程序用户签入
        /// <summary>
        /// 小程序用户签入
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<EmployeeWechatEntity> GetInfoByLogin(string openid)
        {
            return await _db.Queryable<EmployeeWechatEntity>().Where(p => p.OpenId.Equals(openid)).FirstAsync();
        }
        #endregion
    }
}
